package com.equis.architecture.preloader {
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	
	/**
	 * Item to use in @see ar.com.mindset.flexy.util.AsyncMultiCaller. Receives an object, a method to call on that object, and an event to wait that object to dispatch.
	 */
	public class BatchItem extends AbstractBatchItem {
		
		protected var host:IEventDispatcher;
		protected var callMethodName:String;
		protected var eventName:String;

		public function BatchItem(_host:IEventDispatcher, _callMethodName:String, _eventName:String, _requires:Array = null, ... _params) {
			super(_requires);
			this.params = _params;
			this.host = _host;
			this.callMethodName = _callMethodName;
			this.eventName = _eventName;
		}

		public override function call(_preCallback:Function):void {
			host.addEventListener(eventName, onEvent);
			host.addEventListener(ErrorEvent.ERROR, onError);
			super.call(_preCallback);
			var f:Function = (host[callMethodName] as Function)
			f.apply(host, params);
		}
		
		protected function onEvent(event:Event):void {
			host.removeEventListener(eventName, onEvent);
			host.removeEventListener(ErrorEvent.ERROR, onError);
			
			preCallback();
			complete = true;
		}
		
		protected function onError(errorEvent:ErrorEvent):void {
			host.removeEventListener(eventName, onEvent);
			host.removeEventListener(ErrorEvent.ERROR, onError);

			preCallback(errorEvent.text);
		}

		public override function toString():String {
			return "Host: " + host + "; Method: " + callMethodName + "; Event: " + eventName;
		}
	}
}